# -*- coding:utf-8 -*-
from django.http import HttpResponse
from django.shortcuts import render, redirect
from django.template import loader
import json
from . import switchInfoMng

# Create your views here.

user_info = {
    'lily': {'pwd': '123'},
    'ly': {'pwd': '123'},
    'rose': {'pwd': '123'}
}




def login(request):
    if request.method == 'POST':
        u = request.POST.get('uu')
        p = request.POST.get('pp')
        s = request.POST.get('ss')
        if user_info.get(u):
            if p == user_info.get(u).get('pwd'):
                # 生成随机字符串保存在cookie中 sessionid : xxxxx
                # 保存在session中（数据库）
                # 在服务端,每个随机字符串对应一个字典,保存信息
                request.session['user111'] = u
                request.session['is_login'] = True
                daySceond = 60*60*24
                # 设置自动注销登录
                if s == '1':
                # 括号中数字单位为秒
                    request.session.set_expiry(daySceond)
                elif s == '2':
                    request.session.set_expiry(7*daySceond)
                elif s == '3':
                    request.session.set_expiry(30*daySceond)

                return redirect('/index/')
    return render(request, 'login.html')

def index(request):
    u = request.session.get('user111')
    if request.session.get('is_login', None):
        return index2(request)
    else:
        return render(request, 'login.html')

def index2(request):
    posts_list = switchInfoMng.getall()
    content = {'posts_list': posts_list}
    template = loader.get_template('index.html')

    return HttpResponse(template.render(content, request))

def add(request):
    if request.method == 'POST':
        id = request.POST.get('id')
        addr = request.POST.get('addr')
        h5switch = request.POST.get('h5switch')
        aspectRatio = request.POST.get('aspectRatio')
        zhifu = request.POST.get("zhifu")
        switchInfoMng.add({"id": str(id),"h5switch" : str(h5switch), "addr":str(addr), "zhifu": str(zhifu), "aspectRatio": str(aspectRatio) })
    return index2(request)

def logout(request):
    request.session.clear()
    return redirect('/login/')

#item点击更改按钮之后
def editItem(request):
    if 'appid' in request.GET:
        id = request.GET['appid']
        item = switchInfoMng.getItem(id)

        content = {'post': item}
        template = loader.get_template('edit.html')
        return HttpResponse(template.render(content, request))
    return index2(request)

def edit(request):
    if request.method == 'POST':
        id = request.POST.get('id')
        addr = request.POST.get('addr')
        h5switch = request.POST.get('h5switch')
        aspectRatio = request.POST.get('aspectRatio')
        zhifu = request.POST.get("zhifu")
        #return  HttpResponse(str({"id": str(id), "h5switch": str(h5switch), "addr": str(addr),"zhifu": str(zhifu), "aspectRatio": str(aspectRatio) }))
        switchInfoMng.edit({"id": str(id), "h5switch": str(h5switch), "addr": str(addr),  "zhifu": str(zhifu), "aspectRatio": str(aspectRatio)})
    return index2(request)

def delete(request):
    if 'appid' in request.GET:
        id = request.GET['appid']
        switchInfoMng.delete(id)
    return index2(request)


def switchInfo(request):
    return QueryInfoByRequest(request)

def content(request):
    return QueryInfoByRequest(request)

def QueryInfoByRequest(request):
    appid = None
    idfa = None

    if 'appid' in request.headers:
        appid = request.headers['appid']
    if 'idfa' in request.headers:
        idfa = request.headers['idfa']

    if 'appid' in request.GET:
        appid = request.GET['appid']
    if 'idfa' in request.GET:
        idfa = request.GET['idfa']

    if 'appid' in request.POST:
        appid = request.POST['appid']
    if 'idfa' in request.POST:
        idfa = request.POST['idfa']

    if request.body is not None:
        print('request.body:' + str(request.body))
        if is_json(request.body):
            dic = json.loads(request.body)
            if 'appid' in dic:
                appid = dic['appid']
            if 'idfa' in dic:
                idfa = dic['idfa']
            for key in dic:
                print(key + ':' + dic[key])

    return QueryInfo(appid, idfa)

def is_json(myjson):
    try:
        json_object = json.loads(myjson)
    except ValueError:
        return False
    return True

def QueryInfo(appid, idfa):
    if idfa is not None:
        print('get idfa:' + str(idfa))

    if appid is not None:
        id = str(appid)
        print('get appid1:' + str(appid))
        item = switchInfoMng.getItem(id)
        if not item:
            rstr = r'{"errorCode":" -1", "errorMsg": "unknow"}'
            return BuildResponse(rstr)
        print('get appid3:' + str(appid))
        state = 1
        addr = item.get("addr")
        zhifu = item.get("zhifu")
        aspectRatio = 1
        if item.get("h5switch") == '0':
            # 正在审核中
            rstr = r'{"errorCode": "-1", "errorMsg": "unknow"}'
            return BuildResponse(rstr)
        if item.get("aspectRatio") == '0':
            aspectRatio = 0
        ios_shenhe_json = '"ios_shenhe":"' + str(state) + '",'
        addr_json = '"addr":"' + str(addr) + '",'
        zhifu_json = '"zhifu":"' + str(zhifu) + '",'
        aspect_j = '"aspectRatio":"' + str(aspectRatio) + '"'

        rstr = r'{"errorCode": "0", "errorMsg": "", "responseData": {' + ios_shenhe_json + addr_json + zhifu_json + aspect_j + '}}'
        return BuildResponse(rstr)

    rstr = r'{"errorCode": "-1", "errorMsg": "unknow"}'
    return BuildResponse(rstr)

def BuildResponse(rstr):
    print('response:', rstr)
    return HttpResponse(rstr)



